<?php
/**
 * 转盘管理
 * User: admin
 * Date: 2018/3/31
 * Time: 15:52
 */

namespace Api\Controller;


class TurntableController extends ApiController
{


    /***
     * 转盘页
     */
    public function index()
    {

        /*!api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);*/
     /*   if(API_UID){
            $uid = API_UID;
            $member = M('member')->where('uid=' . $uid)->find();
            $result_data['is_exchange'] = $member['is_exchange']?$member['is_exchange']:0;
        }else{
            $result_data['is_exchange'] = 0;
        }*/

        $result_data = array();
        //是否惠go币抵扣元宝


        $periods= date('YmdHi', time());
        //$periods = '201804111549';
        $animals = M('animal')->field('id,name,beishu')->order('id desc')->select();
        foreach ($animals as &$an){
            $where['periods'] = $periods;
            $where['bet_animal'] = $an['id'];
            $total = M('bets')->where($where)->field('sum(money) as total')->find();
            $bets = $total['total'];
            $bets = $this->format_money($bets);
            $an['total_money'] = $bets ? $bets : 0;
        }
       // $miao = date('s', time()); echo $miao;
        //上轮中奖记录
        $last_lot=M('winner_records')->order('uptime desc')->find();
        // echo M('lottery_record')->getLastSql();
        $lottery_record = M('lottery_record')->order('uptime desc')->limit(10)->select();
        $big_winner = M('winner_records')->where('periods='.$last_lot['periods'])->order('total_money desc')->find();
        //echo M('winner_records')->getLastSql();
        if($big_winner) {
            $ucenter_member= M('ucenter_member')->where('id=' . $big_winner['uid'])->find();
            if($ucenter_member['user_type'] == 3){
                $num =substr_replace($big_winner['total_money'], '0', -3, -2);
                $total_money =$this->zhengchu($num,$big_winner['times']);
                $total_money =  $this->format_money($total_money);
                $big_winner['total_money'] = $total_money;
            }else {
                $big_winner['total_money'] = $this->format_money($big_winner['total_money']);
            }

            $avatar = M('member')->where('uid=' . $big_winner['uid'])->getField('avatar');

            $big_winner['avatar']=$avatar;
           // $big_winner['nickname'] = M('member')->where('uid=' . $big_winner['uid'])->getField('nickname');
            $usernmae=M('ucenter_member')->where('id='.$big_winner['uid'])->getField('username');
            $nickname =M('member')->where('uid='.$big_winner['uid'])->getField('nickname');
            if($usernmae == $nickname){
                $big_winner['nickname'] =substr_replace($nickname,'****',3,4);
            }else {
                $big_winner['nickname'] = $nickname;
           }
        }

        //排行
        $rank_list=M('winner_records')->order('id desc')->group('periods')->limit(10)->select();
        //echo M('winner_records')->getLastSql();
                    

        $ranks = array();
        foreach ($rank_list as $rank){
            $r_list = M('winner_records')->where('periods='.$rank['periods'])->order('total_money desc')->limit(4)->select();
            $ranks = array_merge($ranks,$r_list);
        }

        $rank_lists=array();
        foreach ($ranks as $key=>$val){
            $member = M('member')->where('uid='.$val['uid'])->find();
            $ucenter_member = M('ucenter_member')->where('id='.$val['uid'])->find();
            $val['nickname'] = substr_replace($ucenter_member['username'],'****',3,4);
            $val['avatar'] = $member['avatar'];
            //$val['money'] = $val['total_money'];
            if($ucenter_member['user_type']==3){
                $num =substr_replace($val['total_money'], '0', -3, -2);
                $total_money =$this->zhengchu($num,$val['times']);
                $total_money =  $this->format_money($total_money);
                $val['total_money'] = $total_money;
            }else{
                $total_money =  $this->format_money($val['total_money']);
                $val['total_money'] = $total_money;
            }

            $val['uptime']=date('m.d H:i', $val['uptime']);
            if($key>9){
                break;
            }else{
                $rank_lists[]= $val;
            }
        }
        //中奖排行榜记录
        $result_data['rank_list'] = $rank_lists?$rank_lists:array();
        //中奖记录
        $result_data['lottery_record'] = $lottery_record?$lottery_record:array();
        //最大赢家
        $result_data['big_winner'] = $big_winner?$big_winner:'';
        //中奖动物
        $result_data['win_animal'] = $last_lot['bet_animal']?$last_lot['bet_animal']:1;
        //下注列表
        $result_data['bet_record'] = $animals?$animals:array();
        $date = date('s', time());
        $result_data['date']= $date;
        $nowtime = date('YmdHi', time());
        $result_data['nowtime']= $nowtime;
        $result_data['time']= time();
        response(1, $result_data);
    }

    /**
     * 下注
     */
    public function bet()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        $is_exchange = I('is_exchange')?I('is_exchange'):0;
        $animal_id = I('bet_animal');
        $money = I('money');
        $data['uid'] = $uid;
        $periods = date('YmdHi', time());
        $data['periods'] = $periods;
        $data['bet_animal'] = $animal_id;
        $data['money'] = $money;
        $animal = M('animal')->where('id=' . $animal_id)->find();
        if ($animal) {
            $data['times'] = $animal['beishu'];
        } else {
            response(-1, '', '下注失败，动物没有找到');
        }

        //是否达到下注封顶
        $total_map['periods'] = $periods;
        $total_map['bet_animal'] = $animal_id;
        $total_map['is_robot'] = 0;
        $total_map['uid'] = $uid;
        $user_total=M('bets')->where($total_map)->field('sum(money) as total_money ')->find();
        $user_total=$user_total['total_money'];
        $animal_total=$animal['user_total']*1000;
        //var_dump($user_total);
        //var_dump($animal_total);
        $user_total = $user_total+$money;
        if($user_total >= $animal_total){
            response(-2, '', '下注金额过大，超过下注量封顶');
        }

        $member = M('member')->where('uid=' . $uid)->find();
        if ($money > $member['coin']) {
            if ($is_exchange) {
               $amount = $member['amount'] * 1000;
                if ($amount >= $money) {
                    $amount = $amount-$money;
                    $amount = $amount/1000;
                    M('member')->where('uid='.$uid)->setField('amount', $amount);
                    //下注，消费记录
                    payrecord($uid,$periods,$money,2,0);
                } else {
                    response(-3, '', '惠GO币不足');
                }

            }else {
                response(-3, '', '元宝不足');
            }
        } else {
            $User=M('member');
            $User->startTrans();
            $User->where('uid=' . $uid)->setDec('coin', $money);
            $yu_coin = $User->where('uid=' . $uid)->getField('coin');
            if($yu_coin < 0){
                $User->rollback();
                response(-3, '', '元宝不足');
            }else{
                $User->commit();
                //下注，消费记录
                payrecord($uid,$periods,$money,2,0);
            }
        }

        $data['uptime'] = time();
        $result = M('bets')->add($data);


        if ($result) {
            $member = M('member')->where('uid=' . $uid)->field('uid,coin,amount')->find();
            $date = date('s', time());
            $member['date']= $date;
            $nowtime = date('YmdHi', time());
            $member['nowtime']= $nowtime;
            response(1, $member);
            //$flag=  R('Push/pushOrder',array($title,''));
        }else{
            response(-2, '', '下注失败');
        }

    }


    /**
     * 查询开奖接口
     */
    public function award_results(){
        $periods = I('periods');
        //上轮中奖记录
        $award=M('lottery_record')->where('periods='.$periods)->order('uptime desc')->find();
        $win_id=$award['bet_animal'];
        //中奖人记录
        $lot_where['periods'] = $periods;
        $lot_where['bet_animal'] = $win_id;
        $list = M('bets')->where($lot_where)->group('uid')->select();
        $win_uid= array();
        foreach ($list as $key=>$li){
            $lot_where['uid']=$li['uid'];
            $win=M('bets')->where($lot_where)->field('sum(money) as total,times')->find();
            $total_money = $win['total']*$win['times'];

            //中奖增加元宝
            //M('member')->where('uid='.$li['uid'])->setInc('coin',$total_money);
            //中奖，消费记录
           // payrecord($li['uid'],$periods,$total_money,3,0);
            if($li['uid']){
            	$win_uid[$key]['uid']= $li['uid'];
            	$win_uid[$key]['win_money']= $total_money;
        	}
        }
        $last_record=M('winner_records')->order('uptime desc')->find();

        $lottery_record = M('lottery_record')->order('uptime desc')->limit(10)->select();
        $big_winner = M('winner_records')->where('periods='.$last_record['periods'])->order('total_money desc')->find();
        $ucenter_member= M('ucenter_member')->where('id=' . $big_winner['uid'])->find();
        if($ucenter_member['user_type'] == 3){
            $num =substr_replace($big_winner['total_money'], '0', -3, -2);
            $total_money =$this->zhengchu($num,$big_winner['times']);
            $total_money =  $this->format_money($total_money);
            $big_winner['total_money'] = $total_money;
        }else{
            $big_winner['total_money'] = $this->format_money($big_winner['total_money']);
        }
        //$big_winner['total_money'] =  $this->format_money($big_winner['total_money']);
        $big_winner['avatar'] = M('member')->where('uid='.$big_winner['uid'])->getField('avatar');
        //$username= M('ucenter_member')->where('id=' . $big_winner['uid'])->getField('username');
        $usernmae=M('ucenter_member')->where('id='.$big_winner['uid'])->getField('username');
        $nickname =M('member')->where('uid='.$big_winner['uid'])->getField('nickname');
        if($usernmae == $nickname){
            $big_winner['nickname'] =substr_replace($nickname,'****',3,4);
        }else {
            $big_winner['nickname'] = $nickname;
        }
        //排行
        $rank_list=M('winner_records')->order('uptime desc')->group('periods')->limit(10)->select();
        //echo M('winner_records')->getLastSql();
        $ranks = array();
        foreach ($rank_list as $rank){
            $r_list = M('winner_records')->where('periods='.$rank['periods'])->order('total_money desc')->limit(4)->select();
            $ranks = array_merge($ranks,$r_list);
        }
        $rank_lists=array();
        foreach ($ranks as $key=>$val){
            $member = M('member')->where('uid='.$val['uid'])->find();
            $ucenter_member = M('ucenter_member')->where('id='.$val['uid'])->find();
            $val['nickname'] = substr_replace($ucenter_member['username'],'****',3,4);
            //$val['nickname'] = $member['nickname'];
            $val['avatar'] = $member['avatar'];
            //$val['money'] = $val['total_money'];
            if($ucenter_member['user_type']==3){
                $num =substr_replace($val['total_money'], '0', -3, -2);
                $total_money =$this->zhengchu($num,$val['times']);
                $total_money =  $this->format_money($total_money);
                $val['total_money'] = $total_money;
            }else{
                $total_money =  $this->format_money($val['total_money']);
                $val['total_money'] = $total_money;
            }
            $val['uptime']=date('m.d H:i', $val['uptime']);
            if($key>9){
                break;
            }else{
                $rank_lists[]= $val;
            }
        }
        sort($win_uid);
	    array_merge($win_uid);
        //中奖玩家
        $result_data['win_uid'] = $win_uid;
        //中奖记录
        $result_data['lottery_record'] = $lottery_record;
        //最大赢家
        $result_data['big_winner'] = $big_winner;
        //中奖排行榜记录
        $result_data['rank_list'] = $rank_lists;
        //中奖动物
        $result_data['win_animal'] = $win_id;
        if(!$win_id){
            response(-2,'','结算中');
        }
        response(1,$result_data);
    }




    /*
    * 经典的概率算法，
    * $proArr是一个预先设置的数组，
    * 假设数组为：array(100,200,300，400)，
    * 开始是从1,1000 这个概率范围内筛选第一个数是否在他的出现概率范围之内，
    * 如果不在，则将概率空间，也就是k的值减去刚刚的那个数字的概率空间，
    * 在本例当中就是减去100，也就是说第二个数是在1，900这个范围内筛选的。
    * 这样 筛选到最终，总会有一个数满足要求。
    * 就相当于去一个箱子里摸东西，
    * 第一个不是，第二个不是，第三个还不是，那最后一个一定是。
    * 这个算法简单，而且效率非常 高，
    * 关键是这个算法已在我们以前的项目中有应用，尤其是大数据量的项目中效率非常棒。
    */
    function get_rand($proArr)
    {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }

    /**
     * 格式化金额
     * @param $money
     */
    function format_money($money){
        if ($money >= 10000) {
            $money = ($money / 10000) ;
            $money = round($money,1). '万';
        } else {
            $money = $money;
        }
        return $money?$money:0; 
    }

    /**
     * 整除
     */
    function zhengchu($num,$times){
        while (1==1){
            if ($num % $times == 0){
                if($num%1000 ==0){
                    return $num;
                }else{
                    $num= $num-1000;
                }
              //return $num;
            }else{
                $num= $num-1000;
            }
        }
    }

}